<?php
namespace app\api\logic;

use app\common\model\XiluhouseSubway;
use app\common\model\XiluhouseSubwayPlatform;
use app\common\model\xiluhouse\Rental;
use app\common\model\xiluhouse\RentalRequest;
use app\common\model\xiluhouse\Village;

class SubwayLogic
{
    public function getList($params)
    {
        $where = [];
        
        // 城市筛选
        if (!empty($params['city'])) {
            $where['name_city'] = ['like', $params['city'] . '%'];
        }
        
        // 关键词搜索
        if (!empty($params['keywords'])) {
            $where['name|code'] = ['like', '%' . $params['keywords'] . '%'];
        }

        $fields = ['id', 'name', 'name_city', 'code'];
        $data = XiluhouseSubway::where($where)
            ->field($fields)
            ->order('id desc')
            ->select();
            
        // 获取每条地铁线对应的站点
        if ($data) {
            // 默认type为1(房源)
            $type = isset($params['type']) ? intval($params['type']) : 1;
            
            foreach ($data as &$item) {
                $stations = XiluhouseSubwayPlatform::where('find_in_set("'.trim($item['code']).'",subways)')
                    ->field(['id', 'name', 'code', 'lng', 'lat', 'subways'])
                    ->select();
                    
                // 统计每个站点的数量
                foreach ($stations as &$station) {
                    if ($type == 1) {
                        // 统计房源数量 - 通过小区关联
                        $station['count'] = Rental::alias('r')
                            ->join('xiluhouse_village v', 'r.village_id = v.id')
                            ->where('v.subway_platform_id', $station['id'])
                            ->where('r.status', 'normal')
                            ->where('r.deletetime', null)
                            ->where('r.apply_status', 1)
                            ->where('v.status', 'normal')
                            ->where('v.deletetime', null)
                            ->where('v.check_status', 1)
                            ->count();
                    } else {
                        // 统计求租信息数量
                        $station['count'] = RentalRequest::where('metro_station_id', $station['id'])
                            ->where('status', 'normal')
                            ->where('is_delete', 2)
                            ->where('apply_status', 1)
                            ->count();
                    }
                }
                
                $item['list'] = $stations;
            }
        }
        
        return $data;
    }
} 